import type { App } from 'vue'
import dayjs, { relativeTime } from '@/utils/date-time'

export default function vFormatTime(app: App<Element>) {
  // 默认返回格式
  let defaultStyle = 'YYYY-MM-DD HH:mm:ss'
  app.directive('format-time', {
    created(el, bindings) {
      if (bindings.value) {
        defaultStyle = bindings.value
      }
    },
    mounted(el, bindings) {
      const textContent = el.textContent
      let textNumber = new Date(textContent).getTime()
      // 如果时间错不是毫秒 转化为毫秒
      if (textContent.length <= 10) {
        textNumber = textNumber * 1000
      }
      // 默认返回时间格式
      // @ts-ignore
      el.textContent = dayjs(textNumber).format(defaultStyle)

      // 获取是否传入指令配置
      Object.keys(bindings.modifiers).forEach((item) => {
        // 如果为查询倒数几天
        if (item === 'relative') {
          // @ts-ignore
          el.textContent = relativeTime(textNumber)
        }
      })
    }
  })
}
